/*
 * Copyright @ 2025 weili23
 * com.example.ai.config 15:19
 * All right reserved.
 */

package com.example.ai.config;

import com.example.ai.bean.ChatMessages;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @desc:设置mongodb为持久化ss
 * @author: weili23
 * @createTime: 2025/4/30 15:19
 * @version: v1.0
 */
@Component
public class MongoDbChatMemoryConfig implements ChatMemoryStore {
    @Autowired
    private MongoTemplate  mongoTemplate;
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        //ChatMessages chatMessages = mongoTemplate.findById(memoryId, ChatMessages.class);
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query  query = new Query(criteria);
        ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);
        if (chatMessages == null) {
            return List.of();
        }
        //content转换为ChatMessage
        String contentJson = chatMessages.getContent();
        //List<ChatMessage> chatMessage = ChatMessageDeserializer.messageFromJson(content);
        //messagesFromJson 和 messageFromJson返回的类型不一样
        return ChatMessageDeserializer.messagesFromJson(contentJson);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        //可以用 messageId或用_id都可以.
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query  query = new Query(criteria);
        Update update = new Update();
        //列表转成json
        String messagesToJson = ChatMessageSerializer.messagesToJson(list);
        update.set("content",messagesToJson);
        //upsert 如果有就修改，没有的话就新增数据
        mongoTemplate.upsert(query,update,ChatMessages.class);

    }

    @Override
    public void deleteMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        mongoTemplate.remove(query,ChatMessages.class);
    }
}
